<?php
/**
 * Viewer ini menerima data dalam sebuah array 'data', yang minimal berisi:
 * ['metadata']
 *        ['n_tables']     = no of table involved
 *        ['pri_table']     = name of primary table
 *        ['n_fields']    = banyaknya field pada tabel
 *        ['fields']        = array berisi informasi field-field tabel
 *            ['name']        = nama field pada tabel
 *            ['alias']        = displayed name dari field
 *            ['type']        = tipe field tabel (converted)
 *            ['values']    = list of possible values, only for ENUM
 *            ['nullable']    = if true: cannot enter null as value
 *            ['editable']    = if false: read only
 *            ['viewable']    = if false: hidden
 *        ['fields_list']    = array berisi daftar field-field tabel     
 *        ['fields_aliases']
 *                        = array berisi mapping alias field-field tabel
 *        ['keys']        = array berisi keys dari tabel 
 *            ['primary']    => Primary Keys
 *                [table]                    of table 'table'
 *                ['name']  = key name, usually PRIMARY
 *                ['value'] = single value or array if composite 
 *
 * ['data']
 *            ['n_all_records']    = banyaknya record pada table
 *            ['first']            = array berisi record pertama table
 *            ['previous']        = array berisi record sebelumnya pada table
 *            ['current']            = array berisi record yang dipilih
 *            ['next']            = array berisi record selanjutnya pada table
 *            ['last']            = array berisi record terakhir table
 */
//print_r_pre($data);
//print_r_pre($options);
//---------- EKSTRAK $data menjadi $metadata dan $data
extract($data);

$foreigners = $metadata['keys']['foreign'];
//print_r_pre($foreigners);


//---------- GET SETTINGS FROM CONFIG FILE
include_once "_get_settings.php";

//---------- BUILD HEADER TABLE
// $table_fields: daftar fields yang viewable
// $table_fileds_idx: index dari $table_fileds pada $metadata['fields'];
$table_fields = array();
$table_fields_idx = array();
foreach ($metadata['fields'] as $idx => $val) {
    $table_field_idx = $idx;
    $table_field = $val['name'];

    if (!$val['autovalue']) {
        $table_fields[] = $table_field;
        $table_fields_idx[] = $table_field_idx;
    }
}

//print_r_pre($table_fields);

// $table_header['fields'] = $table_fields, tetapi nama field diubah menjadi aliasnya, jika didefinisikan
$table_header = array();
foreach($table_fields as $idx => $field) {
    $table_header['fields'][$idx] = $metadata['fields_aliases'][$field];
}

//print_r_pre($table_header);

//---------- BUILD ISI TABLE
$table_content = array();

$datetime_picker = array();

foreach ($table_fields as $idx => $field) {
    $field_meta = $metadata['fields'][$metadata['fields_numbers'][$field]];
    
    //print_r_pre($field_meta);
    
    //check field type
    $type = $field_meta['type'];

    //echo $idx." -> ".$field." ".$type."<BR />";

    $set_value = $data['current'][$field];
    $attr = '';
    
    $input = '';
    $info = '';
        
    if ($field_meta['nullable']) {
        $filled = !is_null($set_value);
        $readOnly = !$filled;
    }
    
    if ($readOnly) {
		$attr .= ' onclick="this.readOnly = false; document.forms[\'input_form\'].elements[\'_null_'.$field.'\'].checked = false; refreshReadOnlyStyle(\'input_form\', \''.$field.'\');"';
		$str_bool_readOnly = "true";
    } else {
        $str_bool_readOnly = "false";
    }
    
    if ((!$field_meta['editable']) && (isset($data['current']))) {
        $attr .= ' disabled="disabled"';
    }
    
    // check if current field is foreign key
    
    if (!is_empty($foreigners) && isset($foreigners[$field_meta['table']]) && is_array($foreigners[$field_meta['table']])) {
        foreach ($foreigners[$field_meta['table']] as $fki => $fkv) {
            if (!is_array($fkv['value'])) {
                $fkv['value'] = array($fkv['value']);
            }
            if (in_arrayi($field, $fkv['value'])) {
                $fk_table = $fkv['fk_table'];
                $fk_value = $fkv['fk_value'];
                $type = "FK";
            }
        }
    }
    //Set Atribute
	if($field == 'key'){
		$attr .= 'onkeyup="strip_key(this)"';
	}
    
    // create input box based on type
        
    switch (strtoupper($type)) {
        case "FK":
			$i++;
			if($i=='1'){   // handle copier just for master fk
				$attr = rtrim($attr,'"').'copy_value(this);"';
			}
			
            $input = $this->common->create_fk_lov($field, $set_value, $fk_table, $fk_value, $unit_controller, $attr);
            break;
    
    
        case "DATE":
            $attr .= ' id="datetime_'.$field.'"';
            $datetime_picker[$field] = 'date';
            $input = form_input($field, $set_value, $attr);
            $info = 'Format: yyyy-mm-dd';
            break;

        case "DATETIME":
            $attr .= ' id="datetime_'.$field.'"';
            $datetime_picker[$field] = 'datetime';
            $input = form_input($field, $set_value, $attr);
            $info = 'Format: yyyy-mm-dd hh:mm';
            break;

        case "TIME":
            $attr .= ' id="datetime_'.$field.'"';
            $datetime_picker[$field] = 'time';
            $input = form_input($field, $set_value, $attr);
            $info = 'Format: hh:mm';
            break;
            
        case "STRING":
			
            $input = form_input($field, $set_value, $attr);
            break;

        case "PASSWORD":
            $input = form_password($field, $set_value, $attr);
            break;

        case "TEXT":
            $input = form_textarea($field, $set_value, $attr);
            break;
            
        case "INTEGER":
            $input = form_input($field, $set_value, $attr);
            break;

        case "REAL":
            $input = form_input($field, $set_value, $attr);
            break;

        case "NUMERIC":
            $input = form_input($field, $set_value, $attr);
            break;

        case "CURRENCY":
            $input = form_input($field, $set_value, $attr);
            break;        

        case "BOOLEAN":
            $attr .= ' onchange="updateBooleanCheckBox(\'input_form\', \''.$field.'\')" onclick="updateBooleanCheckBox(\'input_form\', \''.$field.'\')"';
            $input = form_checkbox('_checkbox_'.$field, 1, false, $attr);
            $input .= form_hidden($field, $set_value);
            $input .= '<script type="text/javascript">updateBooleanCheckBox(\'input_form\', \''.$field.'\');</script>';
            break;
            
        case "ENUM":
            $options = $field_meta['values'];
            $input = form_dropdown($field, $options, $set_value, $attr); break;

        case "FILE":
            $input = form_upload($field, $set_value, $attr);
            if (!is_null_or_false($field_meta['properties']['original_filename']) && !is_empty($field_meta['properties']['original_filename'])) {
                $filename = $field_meta['properties']['original_filename'];
                $input .= form_hidden('_filename_'.$field, $filename);
            }
            break;

        case "IMAGE":
            $input = form_upload($field, $set_value, $attr);
            if (!is_null_or_false($field_meta['properties']['original_filename']) && !is_empty($field_meta['properties']['original_filename'])) {
                $filename = $field_meta['properties']['original_filename'];
                $input .= form_hidden('_filename_'.$field, $filename);
            }
            break;            
            
        default:
            $input = form_input($field, $set_value, $attr);
            break;
    }    

    if ($field_meta['nullable'])
        $null = form_checkbox('_null_'.$field, '', is_null($set_value), ' onchange="toogleReadOnly(\'input_form\', \''.$field.'\')" onclick="toogleReadOnly(\'input_form\', \''.$field.'\')"').' <strong><small>null</small></strong>';
    else
        $null = '';
    
    $table_content[] = array($table_header['fields'][$idx], $input._MED_SEP.'<span class="field_info">'.$info.'</span>
    <script type="text/javascript">
        document.forms[\'input_form\'].elements[\''.$field.'\'].readOnly = '.$str_bool_readOnly.';
        refreshReadOnlyStyle(\'input_form\', \''.$field.'\');
    </script>', $null);
}

//print_r_pre($table_content);

//---------- TAMBAHKAN ACTIONS
// modify content

// modify footer

$table_footer_str  = '<td align="center" colspan="0">';
$record = 'record/'.$data['current']['id']; //XXX: assuming every record follows our convention: has id field
$first_record = 'record/'.$data['first']['id'];
if (isset($data['previous']['id'])) {
    $prev_record = 'record/'.$data['previous']['id'];
} else {
    $prev_record = 'record/'.$data['last']['id'];
}

if (isset($data['next']['id'])) {
    $next_record = 'record/'.$data['next']['id'];
} else {
    $next_record = 'record/'.$data['first']['id'];
}
$last_record = 'record/'.$data['last']['id'];
$arr_template = array_merge(array('SAVE_BUTTON' => form_submit('__submit_save', 'Save'), 'RECORD_ID' => $data['current']['id'], 'RECORD' => $record, 'FIRST_RECORD' => $first_record, 'PREV_RECORD' => $prev_record, 'NEXT_RECORD' => $next_record, 'LAST_RECORD' => $last_record), $label_template);

foreach ($actions['left'] as $aidx => $aval) {    
    $table_footer_str .= str_from_template($aval, $arr_template)._WIDE_SEP;
}
foreach ($actions['center'] as $aidx => $aval) {    
    $table_footer_str .= str_from_template($aval, $arr_template);
}
foreach ($actions['right'] as $aidx => $aval) {    
    $table_footer_str .= _WIDE_SEP.str_from_template($aval, $arr_template);
}

// add datetime picker script
if (!is_empty($datetime_picker)) {
    $table_footer_str .= '<script type="text/javascript">';
    foreach ($datetime_picker as $field => $type) {
        if (strcasecmp($type, 'time')==0) {
            $table_footer_str .= '
                jQuery(function() {
                    jQuery(\'#datetime_'.$field.'\').kmTimepicker({
                        time24h: true,
                        timeFormat: "HH:ii"
                     });
                });
            ';
        } else { // datetime or date
            $table_footer_str .= '
                jQuery(function() {
                    jQuery(\'#datetime_'.$field.'\').datepicker({
                        duration: \'\',
                        showTime: ';
            $table_footer_str .= (strcasecmp($type, 'datetime')==0)?'true':'false';
            $table_footer_str .= ',
                        time24h: true,
                        dateFormat: "yy-mm-dd",
                        constrainInput: false
                     });
                });
            ';
        }
    }
    $table_footer_str .= '</script>';
}

$table_footer_str  .= '</td>';

$table_footer[] = $table_footer_str;


//---------- DISPLAY TABLE
$table_data = compact('table_header', 'table_content', 'table_footer', 'label', 'table_records_per_page');
echo form_open_multipart($form['action'], array_merge(array('name' => 'input_form'), $form['attributes']));
$this->load->view('form/columnar_table', $table_data);
echo form_close();

/* EOF views/form/columnar.php */